package com.adcc.ags.agent.healthcheck;

import com.adcc.utility.log.Log;
import com.codahale.metrics.health.HealthCheck;
import com.fasterxml.jackson.databind.ObjectMapper;
import jersey.repackaged.com.google.common.collect.Lists;
import jersey.repackaged.com.google.common.collect.Maps;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;

import java.util.List;
import java.util.Map;

/**
 * CPU健康检查
 */
public class CPUHealthCheck extends HealthCheck{

    @Override
    protected Result check() {
        Sigar sigar = null;
        try{
            sigar = new Sigar();
            List<Map<String,Double>> list = Lists.newArrayListWithExpectedSize(4);
            CpuPerc[] cpuPercList = sigar.getCpuPercList();
            for(CpuPerc cpuPerc : cpuPercList){
                double dIdle = cpuPerc.getIdle() * 100;
                double dCombined = cpuPerc.getCombined() * 100;
                Map<String,Double> map = Maps.newHashMapWithExpectedSize(2);
                map.put("idle",dIdle);
                map.put("combined",dCombined);
                list.add(map);
            }
            return Result.healthy(new ObjectMapper().writeValueAsString(list));
        }catch (Exception ex){
            Log.error(CPUHealthCheck.class.getName(),"check() error",ex);
            return Result.unhealthy(ex.fillInStackTrace());
        }finally {
            if(sigar != null){
                sigar.close();
            }
        }
    }
}
